package com.bustle.commons.http;

import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import com.bustle.commons.Converter;

public class XmlToTypeConverter<Type> implements Converter<String, Type>
{
  public XmlToTypeConverter(Class<Type> aClass)
  {
    type = aClass;
  }

  @SuppressWarnings("unchecked")
  @Override
  public Type convert(String aSource)
  {
    try
    {
      String source = new String(aSource.getBytes(), "UTF-8");
      JAXBContext context = JAXBContext.newInstance(type);
      Unmarshaller um = context.createUnmarshaller();
      return (Type)um.unmarshal(new StringReader(source));
    }
    catch (JAXBException | UnsupportedEncodingException anException)
    {
      anException.printStackTrace();
      return null;
    }
  }

  protected Class<Type> type;
}
